package com.sgb.member.ui.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.SparseArray;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.sgb.member.PickCateType;
import com.sgb.member.R;
import com.sgb.member.databinding.FragmentBiddingRegistBinding;
import com.sgb.member.di.DaggerMemberFragComponent;
import com.sgb.member.di.MemberFragModule;
import com.sgb.member.entity.BiddingRegisterBean;
import com.sgb.member.ui.activity.BiddingQuotationActivity;
import com.sgb.member.ui.adapter.BiddingQuotationAdapter;
import com.sgb.member.view_model.BidderQuotationModel;
import com.swgk.core.base.AppLazyFragment;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.view.areapopup.AddressEntity;
import com.swgk.core.view.areapopup.GoodsSourceLocationEntity;
import com.swgk.core.view.areapopup.ThreeLevelAreaWindow;
import com.swgk.core.view.selection.CommonPopEntity;
import com.swgk.core.view.selection.CopyUtils;
import com.swgk.core.view.selection.MemberStatusView;
import com.swgk.core.view.selection.XChooseDialog;
import com.swgk.core.view.selection.XChooseEntity;
import com.swgk.core.xrecyclerview.LoadingMoreFooter;
import com.swgk.core.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 * 竞价报价
 */
public class BiddingQuotationFragment extends AppLazyFragment implements MemberStatusView.OnChooseListener, XChooseDialog.DialogCallBackImpl {

    @Inject
    BidderQuotationModel sModel;
    private FragmentBiddingRegistBinding mBinding;
    private CommonPopEntity mCurEntity;
    private int mCurPos;
    // 经营地址Popup
    private ThreeLevelAreaWindow mAddressPop;
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> scrData;
    private CommonPopEntity mAll;
    private String mNo1 = ""; //  招标类型
    private String mNo2 = ""; // "分类2");
    private String mNo7 = ""; // "概算金额");
    private String mNo8 = ""; // "省份");
    private String mNo9 = ""; // "市区");

    private BiddingQuotationAdapter mAdapter;

    public static BiddingQuotationFragment newInstance(int position, CommonPopEntity entity) {
        BiddingQuotationFragment fragment = new BiddingQuotationFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("INDEX", position);
        bundle.putSerializable("ENTITY", entity);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerMemberFragComponent.builder()
                .appComponent(appComponent)
                .memberFragModule(new MemberFragModule(this))
                .build()
                .inject(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_bidding_regist, container, false);
        mBinding.setLifecycleOwner(this);
        return mBinding.getRoot();
    }

    @Override
    protected void initView() {
        mCurPos = getArguments().getInt("INDEX", 0);
        mCurEntity = (CommonPopEntity) getArguments().getSerializable("ENTITY");
        mAll = new CommonPopEntity();
        mAll.setNo("");
        mAll.setTypeName("全部");
        mBinding.chooseLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int i = 0; i < mNameArray.size(); i++) {
                    XChooseEntity chooseEntity = mData.get(mData.keyAt(i));
                    if (chooseEntity != null) {
                        if (chooseEntity.getList() == null || chooseEntity.getList().size() == 0) {
                            if (chooseEntity.getSort() == PickCateType.TYPE_1 ||
                                    chooseEntity.getSort() == PickCateType.TYPE_7 ||
                                    chooseEntity.getSort() == PickCateType.TYPE_8) {
                                loadOtherData();
                                return;
                            }
                        }
                    }
                }
                mChooseDialog.initData(mData, mFilters);
                mChooseDialog.showDialog();
            }
        });
        initChooseDialog();
        initPopup();
        initRecycler();
    }

    @Override
    protected void onLazyLoad() {
        loadData(false);
        loadOtherData();
    }

    public void loadData(boolean isLoadMore) {
        String text = ((BiddingQuotationActivity) getActivity()).getSearchText();
        sModel.getBidderQuotation(isLoadMore, text, mNo1, mNo2, mNo7, mNo8, mNo9);
    }

    private void loadOtherData() {
        if (isListEmpty(PickCateType.TYPE_1)) {
            sModel.getTenderNewTypeList(PickCateType.TYPE_1, false); // 招标类型
        }
        if (isListEmpty(PickCateType.TYPE_7)) {
            sModel.getProjectMoney(PickCateType.TYPE_7, false); // 招标概算金额
        }
        if (scrData == null || scrData.size() == 0) {
            sModel.getAddressModel(PickCateType.TYPE_8);  // 经营地址
        }
    }

    public void setAddressData(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {
        if (data != null && data.size() > 0) {
            scrData = data;
            if (TextUtils.isEmpty(mNo8)) {
                mAddressPop.setData(data, true);
            } else {
                mAddressPop.setDataAndPosition(data, mNo8, mNo9, "", true, true);
            }
        } else {
            sModel.getAddressModel(PickCateType.TYPE_8);
        }
    }

    /**
     * -------------------------------------initRecycler------------------------------------------
     */
    private void initRecycler() {
        mBinding.recyclerView.setPullRefreshEnabled(true);
        mBinding.recyclerView.setLoadingMoreEnabled(true);
        LoadingMoreFooter footer = (LoadingMoreFooter) mBinding.recyclerView.getFootView();
        footer.setNoMoreHint("已经到底啦~");
        mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mBinding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                loadData(false);
            }

            @Override
            public void onLoadMore() {
                loadData(true);
            }
        });
        mAdapter = new BiddingQuotationAdapter(getActivity(), null);
        mBinding.recyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClick(new AdapterOnItemClick<BiddingRegisterBean>() {
            @Override
            public void onItemClick(BiddingRegisterBean bean, int position) {
                sModel.getUrlSetting(bean.getNo());
            }
        });
    }

    public void closeRecyclerRefreshing() {
        mBinding.recyclerView.refreshComplete();
        mBinding.recyclerView.loadMoreComplete();
    }

    public void showEmpty() {
        mBinding.recyclerView.setVisibility(View.GONE);
        mBinding.empView.setVisibility(View.VISIBLE);
    }

    public void refreshRecycler(List<BiddingRegisterBean> list, boolean isLoadMore, boolean noMoreData) {
        mBinding.recyclerView.setVisibility(View.VISIBLE);
        mBinding.recyclerView.setLoadingMoreEnabled(!noMoreData);
        closeRecyclerRefreshing();
        if (isLoadMore) {
            if (list != null && list.size() > 0) {
                mAdapter.addDatas(list);
            }
        } else {
            if (list != null && list.size() > 0) {
                mBinding.empView.setVisibility(View.GONE);
                mAdapter.setDatas(list);
            } else {
                mAdapter.clearDatas();
                mBinding.empView.setVisibility(View.VISIBLE);
            }
        }
    }

    /**
     * ------------------------------- Popup ---------------------------------------------
     */
    private void initPopup() {
        mBinding.chooseLayout.setVisibility(View.VISIBLE);
        mBinding.popup1.setVisibility(View.VISIBLE);
        mBinding.popup1.setKeyName(mNameArray.get(PickCateType.TYPE_1));
        mBinding.popup2.setVisibility(View.GONE);
        mBinding.popup3.setVisibility(View.VISIBLE);
        mBinding.popup1.initPopup(mBinding.grayLayout, mBinding.popLine, this);
        mBinding.popup2.initPopup(mBinding.grayLayout, mBinding.popLine, this);
        mBinding.popup3.initPopup(mBinding.grayLayout, mBinding.popLine, this);
        mBinding.popup4.initPopup(mBinding.grayLayout, mBinding.popLine, this);
        initAddressPopup();
    }

    private void initAddressPopup() {
        mBinding.popup4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (scrData == null) {
                    sModel.getAddressModel(PickCateType.TYPE_8);
                } else {
                    showAddressPopup();
                }
            }
        });
        mAddressPop = new ThreeLevelAreaWindow(getActivity());
        mAddressPop.setBgView(mBinding.grayLayout);
        mAddressPop.setMemberHeight();
        mAddressPop.setCitySingle();
        mAddressPop.setProvinceSingle();
        mAddressPop.setShowSimpleName(true);
        mAddressPop.setOnlyShowProAndCity(true);
        mAddressPop.setAllSingleSelect(true);
        mAddressPop.setThreeListIsGone(true);
        mAddressPop.setOnResultClick(new ThreeLevelAreaWindow.OnResultClickProxy() {
            @Override
            protected void result(GoodsSourceLocationEntity entity) {
                mNo8 = "";
                mNo9 = "";
                mFilters.put(PickCateType.TYPE_8, mAddressPop.getProvincePosition());
                addMainEntity(PickCateType.TYPE_9, new ArrayList<>());
                mBinding.popup4.updateChooseTextStatus(0, mBinding.popup4.getKeyName());
                if (!TextUtils.isEmpty(entity.getProvinceNo())) {
                    mNo8 = entity.getProvinceNo();
                    mFilters.put(PickCateType.TYPE_8, mAddressPop.getProvincePosition());
                    mBinding.popup4.updateChooseTextStatus(1, entity.getProvinceName());
                    updateCityData(new CommonPopEntity(entity.getProvinceNo(), entity.getProvinceName()), mAddressPop.getProvincePosition(), false);
                    if (!TextUtils.isEmpty(entity.getCityNo())) {
                        mNo9 = entity.getCityNo();
                        mFilters.put(PickCateType.TYPE_9, mAddressPop.getmCityPosition());
                        mBinding.popup4.updateChooseTextStatus(1, entity.getCityName());
                    }
                }
                //刷新数据
                loadData(false);
            }
        });
        mAddressPop.setOnDismissListener(() -> {
            mBinding.popLine.setVisibility(View.GONE);
            if (!TextUtils.isEmpty(mNo8) || !TextUtils.isEmpty(mNo8)) {
                mBinding.popup4.updateChooseTextStatus(1, null);
            } else {
                mBinding.popup4.updateChooseTextStatus(0, mBinding.popup4.getKeyName());
            }
        });
    }

    private void showAddressPopup() {
        mBinding.popLine.setVisibility(View.VISIBLE);
        if (!TextUtils.isEmpty(mNo8) || !TextUtils.isEmpty(mNo9)) {
            mBinding.popup4.updateChooseTextStatus(-2, null);
        } else {
            mBinding.popup4.updateChooseTextStatus(-1, mBinding.popup4.getKeyName());
        }
        mAddressPop.showPopwindow0(mBinding.popLine);
    }


    @Override
    public void onLoadChooseData(String mKeyName) {
        switch (mKeyName) {
            case "竞价类型":
                sModel.getTenderNewTypeList(PickCateType.TYPE_1, false);
                break;
            case "概算金额":
                sModel.getProjectMoney(PickCateType.TYPE_7, false);
                break;
        }
    }

    @Override
    public void onChooseResult(String mKeyName, CommonPopEntity entity, Object... objects) {
        int position = (int) objects[0];
        String no = position == 0 ? "" : entity.getNo();
        switch (mKeyName) {
            case "竞价类型":
                if (!TextUtils.equals(no, mNo1)) {
                    mNo1 = no;
                    mFilters.put(PickCateType.TYPE_1, position);
                    loadTenderSecondType(entity, position, false);
                    loadData(false);
                }
                break;
            case "概算金额":
                if (!TextUtils.equals(no, mNo7)) {
                    mNo7 = no;
                    mFilters.put(PickCateType.TYPE_7, position);
                    loadData(false);
                }
                break;
        }
    }

    /**
     * ------------------------------------ 侧滑刷选 ----------------------------------------
     */

    private XChooseDialog mChooseDialog;
    // 数据集
    private SparseArray<XChooseEntity> mData = new SparseArray<>();
    // 本地缓存筛选结果
    private SparseIntArray mFilters = new SparseIntArray();
    private SparseArray<String> mNameArray;

    // 二级分类关联数据
    private List<Integer> mCateOther;

    private void initChooseDialog() {
        mCateOther = new ArrayList<>();
        mCateOther.add(PickCateType.TYPE_2);
        mCateOther.add(PickCateType.TYPE_21);
        mCateOther.add(PickCateType.TYPE_22);
        mCateOther.add(PickCateType.TYPE_23);
        mCateOther.add(PickCateType.TYPE_24);
        mCateOther.add(PickCateType.TYPE_25);
        mNameArray = new SparseArray<>();
        mNameArray.put(PickCateType.TYPE_1, "竞价类型");
        for (Integer integer : mCateOther) {
            mNameArray.put(integer, "分类");
        }
        mNameArray.put(PickCateType.TYPE_7, "概算金额");
        mNameArray.put(PickCateType.TYPE_8, "省份");
        mNameArray.put(PickCateType.TYPE_9, "市区");
        mChooseDialog = new XChooseDialog(getContext(), mNameArray);
        mChooseDialog.setCallBack(this);
        for (int i = 0; i < mNameArray.size(); i++) {
            int key = mNameArray.keyAt(i);
            addMainEntity(key, new ArrayList<>());
        }
    }

    public void setChooseItemData(int type, List<CommonPopEntity> data) {
        if (data != null && data.size() > 0) {
            String name = data.get(0).getTypeName();
            if (!TextUtils.isEmpty(name) && (!TextUtils.equals("全部", name) && !TextUtils.equals("不限", name))) {
                data.add(0, mAll);
            }
        }
        addMainEntity(type, data);
        switch (type) {
            case PickCateType.TYPE_1:
                mBinding.popup1.setData(data, mNo1);
                break;
            case PickCateType.TYPE_7:
                mBinding.popup3.setData(data, mNo7);
                break;
        }
    }

    public void showLeftDialog(int type, List<CommonPopEntity> data) {
        mChooseDialog.addEntity(type, data);
        mChooseDialog.showDialog();
    }

    public void addMainEntity(int index, List<CommonPopEntity> list) {
        if (mData.get(index) != null) {
            if (list == null || list.size() == 0) {
                mData.get(index).setList(new ArrayList<>());
            } else {
                mData.get(index).setList(list);
            }
        } else {
            mData.put(index, new XChooseEntity(index, mNameArray.get(index), list));
        }
        mFilters.put(index, 0);
    }

    public void addMainEntity(int index, String name, List<CommonPopEntity> list) {
        if (!TextUtils.isEmpty(name)) {
            mNameArray.put(index, name);
        }
        if (mData.get(index) != null) {
            mData.get(index).setTypeName(mNameArray.get(index));
            if (list == null || list.size() == 0) {
                mData.get(index).setList(new ArrayList<>());
            } else {
                mData.get(index).setList(list);
            }
        } else {
            mData.put(index, new XChooseEntity(index, mNameArray.get(index), list));
        }
        mFilters.put(index, 0);
    }

    private boolean isListEmpty(int catType) {
        return mData.get(catType) != null &&
                (mData.get(catType).getList() == null || mData.get(catType).getList().size() == 0);
    }

    @Override
    public void loadChildData(XChooseEntity entity, int pos) {
        switch (entity.getSort()) {
            case PickCateType.TYPE_1:
                loadTenderSecondType(entity.getList().get(pos), pos, true);
                mChooseDialog.showDialog();
                break;
            case PickCateType.TYPE_2:
            case PickCateType.TYPE_21:
            case PickCateType.TYPE_22:
            case PickCateType.TYPE_23:
            case PickCateType.TYPE_24:
            case PickCateType.TYPE_25:
                loadTenderOtherType(entity.getSort(), entity.getList().get(pos), pos, true);
                mChooseDialog.showDialog();
                break;
            case PickCateType.TYPE_8:
                updateCityData(entity.getList().get(pos), pos, true);
                mChooseDialog.showDialog();
                break;
            default:
                break;
        }
    }

    // 更新二级数据
    private void loadTenderSecondType(CommonPopEntity entity, int pos, boolean isShowLeftDialog) {
        int category = !TextUtils.isEmpty(entity.getNo()) ? Integer.parseInt(entity.getNo()) : 0;
        String[] cateTitle = CopyUtils.getCateTitle(pos, category);
        String name1 = cateTitle[0];
        String name2 = cateTitle[1];
        String name3 = cateTitle[2];
        if (isShowLeftDialog) {
            mChooseDialog.addEntity(PickCateType.TYPE_2, name1, new ArrayList<>());
            mChooseDialog.addEntity(PickCateType.TYPE_21, name2, new ArrayList<>());
            mChooseDialog.addEntity(PickCateType.TYPE_22, name3, new ArrayList<>());
            for (Integer integer : mCateOther) {
                mChooseDialog.addEntity(integer, new ArrayList<>());
            }
        } else {
            addMainEntity(PickCateType.TYPE_2, name1, new ArrayList<>());
            addMainEntity(PickCateType.TYPE_21, name2, new ArrayList<>());
            addMainEntity(PickCateType.TYPE_22, name3, new ArrayList<>());
            for (Integer integer : mCateOther) {
                addMainEntity(integer, new ArrayList<>());
            }
        }
        if (pos > 0) {
            sModel.getTenderGoodsCategoryAllList(PickCateType.TYPE_2, entity.getNo(), isShowLeftDialog);
        }
    }

    private void loadTenderOtherType(int sort, CommonPopEntity entity, int pos, boolean isShowLeftDialog) {
        ArrayList<CommonPopEntity> objects = new ArrayList<>();
        for (int i = 0; i < mCateOther.size(); i++) {
            Integer integer = mCateOther.get(i);
            if (integer > sort) {
                if (isShowLeftDialog) {
                    mChooseDialog.addEntity(integer, objects);
                } else {
                    addMainEntity(integer, objects);
                }
            }
        }
        if (pos > 0 && mCateOther.contains(sort + 1)) {
            int index = mCateOther.indexOf(sort) + 1;
            if (entity.getChildren() != null && entity.getChildren().size() > 0) {
                if (isShowLeftDialog) {
                    mChooseDialog.addEntity(mCateOther.get(index), entity.getChildren());
                } else {
                    addMainEntity(mCateOther.get(index), entity.getChildren());
                }
            } else {
                if (isShowLeftDialog) {
                    mChooseDialog.addEntity(mCateOther.get(index), objects);
                } else {
                    addMainEntity(mCateOther.get(index), objects);
                }
            }
        }
    }

    private void updateCityData(CommonPopEntity entity, int pos, boolean isShowLeftDialog) {
        if (isShowLeftDialog) {
            mChooseDialog.addEntity(PickCateType.TYPE_9, new ArrayList<>());
        } else {
            addMainEntity(PickCateType.TYPE_9, new ArrayList<>());
        }
        if (pos > 0) {
            sModel.getAddressCityData(scrData, entity.getNo(), PickCateType.TYPE_9, isShowLeftDialog);
        }
    }

    @Override
    public void result(SparseArray<XChooseEntity> data, SparseIntArray map) {
        mData = CopyUtils.deepPopEntityCopy(data);
        mFilters = map.clone();
        for (int i = 0; i < mData.size(); i++) {
            int key = mData.keyAt(i);
            refreshItemValue(key, mFilters.get(key));
        }
        loadData(false);
    }

    private void refreshItemValue(int key, int value) {
        XChooseEntity entity = mData.get(key);
        mFilters.put(key, value);
        String itemNo = entity.getItemNo(value);
        switch (key) {
            case PickCateType.TYPE_1:
                mNo1 = entity.getItemNo(value);
                mBinding.popup1.refreshChoose(mNo1, entity.getItemName(value), value);
                break;
            case PickCateType.TYPE_2:
                mNo2 = entity.getItemNo(value);
                break;
            case PickCateType.TYPE_21:
            case PickCateType.TYPE_22:
            case PickCateType.TYPE_23:
            case PickCateType.TYPE_24:
            case PickCateType.TYPE_25:
                if (value > 0) {
                    mNo2 = entity.getItemNo(value);
                }
                break;
            case PickCateType.TYPE_7:
                mNo7 = entity.getItemNo(value);
                mBinding.popup3.refreshChoose(mNo7, entity.getItemName(value), value);
                break;
            case PickCateType.TYPE_8: // 省
                mNo8 = itemNo;
                mBinding.popup4.refreshChoose(mNo8, entity.getItemName(value), value);
                mAddressPop.setDefPosition(value, 0);
                break;
            case PickCateType.TYPE_9: // 市
                mNo9 = itemNo;
                mAddressPop.setDefPosition(mFilters.get(PickCateType.TYPE_8), value);
                if (value > 0) {
                    mBinding.popup4.refreshChoose(mNo9, entity.getItemName(value), value);
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void reset() {
        mFilters.clear();
        resetMainData();
        result(mData, mFilters);
        mChooseDialog.initData(mData, mFilters);
        mChooseDialog.showDialog();
    }

    private void resetMainData() {
        for (Integer integer : mCateOther) {
            addMainEntity(integer, new ArrayList<>());
        }
        addMainEntity(PickCateType.TYPE_9, new ArrayList<>());
    }

    @Override
    public void onCancel() {
        mChooseDialog.initData(mData, mFilters);
    }
}
